package com.example.spring.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest2 {

    public static void main(String[] args) {
        final int N = 4;
        CyclicBarrier barrier = new CyclicBarrier(N, new Runnable() {
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                System.out.println(name + "barrier runnable");
            }
        });
        for (int i = 0; i < N; i++) {
            new Thread(new CyclicBarrierTest2.Writer(barrier)).start();
        }

    }

    static class Writer implements Runnable {
        CyclicBarrier barrier;

        public Writer(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println(name + "开始读写数据");
            try {
                Thread.sleep(4000);
                System.out.println(name + "借宿读写数据");
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(name + "所有线程都读取完毕，开始其他的操作");
        }
    }

}


